package com.lottery.entity;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;
public class BaseRequest implements Serializable{

	private static final long serialVersionUID = -9069828195151800473L;
	private static final String CLASS_NAME = "class";

    public String buildCondition() {
        Class<?> requestType = getClass();
        PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(requestType);
        StringBuilder cond = new StringBuilder();
        for (PropertyDescriptor property : pds) {
            String name = property.getName();
            if (StringUtils.equals(name, CLASS_NAME)) {
                continue;
            }
            Field parameterField = ReflectionUtils.findField(requestType, name);
            Condition condition = getAnnotation(parameterField, Condition.class);
            if (condition == null) {
                continue;
            }
            Object val = ReflectionUtils.invokeMethod(property.getReadMethod(), this);
            if (val == null) {
                continue;
            }
            cond.append(name).append("=").append(val).append("&");
        }
        return cond.toString();
    }

    public static <T extends Annotation> T getAnnotation(AnnotatedElement annotatedElement, Class<T> annotationType) {
        try {
            T ann = annotatedElement.getAnnotation(annotationType);
            if (ann == null) {
                for (Annotation metaAnn : annotatedElement.getAnnotations()) {
                    ann = metaAnn.annotationType().getAnnotation(annotationType);
                    if (ann != null) {
                        break;
                    }
                }
            }
            return ann;
        } catch (Exception ex) {
            return null;
        }
    }
}
